﻿-- set an execution quota 
local function set_quota(secs)
 local st=os.clock()
 function check() 
  if os.clock()-st > secs then 
    debug.sethook() -- disable hooks
    error("quota exceeded")
  end
 end
 debug.sethook(check,"",100000);
end

-- The user code is allowed to run for 5 seconds.
set_quota(5)

-- run code under environment:
local function run(untrusted_code)
  local untrusted_function, message = load (untrusted_code, "untrusted code", "t", { print = print })
  if not untrusted_function then return nil, message end
  return pcall(untrusted_function)
end

-- here is the user code:
local userscript = [[
function fib(n) 
 if n<2 then return n
 else return fib(n-2)+fib(n-1)
 end
end
for n=1,42 do print(n,fib(n)) end
]]
-- call it:
local r, m = run(userscript)
print(r, m);